package controllers

import (
	"errors"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	en2 "github.com/go-playground/validator/v10/translations/en"
	zh2 "github.com/go-playground/validator/v10/translations/zh"
	"reflect"
	"strings"
)

var trans ut.Translator

func InitTrans(locale string) (err error) {
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {

		//注册一个获取json tag的自定义方法
		v.RegisterTagNameFunc(func(fld reflect.StructField) string {
			name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
			if name == "-" {
				return ""
			}
			return name
		})
		zhT := zh.New()
		enT := en.New()

		//第一个参数是备用 的语言环境，后边的参数是应该支持的语言环境
		uni := ut.New(enT, zhT, enT)
		//通常取决于http 请求头的 Accept-Language
		var ok bool
		translator, ok := uni.GetTranslator(locale)
		if !ok {
			return errors.New("translator not found")
		}
		//注册翻译器
		switch locale {
		case "en":
			err = en2.RegisterDefaultTranslations(v, translator)
		case "zh":
			err = zh2.RegisterDefaultTranslations(v, translator)
		default:
			err = en2.RegisterDefaultTranslations(v, translator)
		}
		return err
	}
	return
}

// 去除提示信息中的结构体名称
func removeTopStruct(fields map[string]string) map[string]string {
	res := make(map[string]string)
	for k, v := range fields {
		res[k[strings.Index(k, ".")+1:]] = v
	}
	return res
}
